Namespace IO

  ''' <summary>
  ''' Class to create and manage temporary files.
  ''' </summary>
  ''' <remarks></remarks>
  Public Class TempFileManager
    Implements IDisposable
    Private _files As New System.Collections.Generic.List(Of String)
    Private _disposed As Boolean


    ''' <summary>
    ''' List of files currently being managed.
    ''' </summary>
    ''' <returns><see cref="System.Collections.ObjectModel.ReadOnlyCollection(Of String)">List</see> of files.</returns>
    ''' <remarks></remarks>
    Public Function FilesList() As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

      Return New System.Collections.ObjectModel.ReadOnlyCollection(Of String)(Me._files)

    End Function

    ''' <summary>
    ''' Creates a new temporary file.
    ''' </summary>
    ''' <returns><see cref="String">Path</see> to new file.</returns>
    ''' <remarks></remarks>
    Public Function CreateFile() As String

      Dim tempFile As String = My.Computer.FileSystem.GetTempFileName

      Me._files.Add(tempFile)

      Return tempFile

    End Function

    ''' <summary>
    ''' Deletes a temporary file.
    ''' </summary>
    ''' <param name="file"><see cref="String">Path</see> of the temporary file.</param>
    ''' <remarks></remarks>
    Public Sub DeleteFile(ByVal file As String)

      If My.Computer.FileSystem.FileExists(file) Then
        My.Computer.FileSystem.DeleteFile(file)
      End If

      If Me._files.Contains(file) Then
        Me._files.Remove(file)

      End If

    End Sub

    ''' <summary>
    ''' Deletes all temporary files.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub DeleteAllFiles()

      Dim tempFiles() As String = New String(Me._files.Count - 1) {}

      Me._files.CopyTo(tempFiles, 0)

      For Each file As String In tempFiles
        Me.DeleteFile(file)
      Next

    End Sub

    ''' <summary>
    ''' Releases resources used by the <see cref="TempFileManager">TempFileManager</see> object.
    ''' </summary>
    ''' <remarks></remarks>
    Public Overloads Sub Dispose() Implements IDisposable.Dispose
      Me.Dispose(True)
      GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
      If Not (Me._disposed) Then
        ' If disposing equals true, dispose all managed 
        ' and unmanaged resources.
        If (disposing) Then
          ' Dispose managed resources.
          Me.DeleteAllFiles()
        End If
      End If
      Me._disposed = True
    End Sub

    Protected Overrides Sub Finalize()
      Me.Dispose(False)
    End Sub

    Public Sub New()
    End Sub

  End Class

End Namespace